package com.qire.antsView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import com.qire.antsView.graphicsFilter.BlurBuilder;
import com.qire.antsView.graphicsFilter.FastBlur;

import androidx.annotation.Nullable;

public class CoverFilterView extends View {

    private View targetView;
    private Bitmap bitmap;
    private Canvas canvas;

    public CoverFilterView(Context context) {
        super(context);
        init();
    }

    public CoverFilterView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CoverFilterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        Context         context = getContext();
        DisplayMetrics  dm      = new DisplayMetrics();

        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int screenWidthPixels   = dm.widthPixels;
        int screenHeightPixels  = dm.heightPixels;

        bitmap = Bitmap.createBitmap(screenWidthPixels, screenHeightPixels, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
    }

    public void setTargetView(View targetView) {
        this.targetView = targetView;
    }

    public void open() {
        if(targetView == null) {
            return;
        }
        new Thread(() -> {
            targetView.draw(canvas);

            boolean lessThan_JELLY_BEAN_MR1 = Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1;
            Bitmap coverLayerImg = lessThan_JELLY_BEAN_MR1 ? FastBlur.doBlur(bitmap, 70, true) : BlurBuilder.blur(getContext(), bitmap, 1f, 14f);
            canvas.drawBitmap(coverLayerImg, 0, 0, new Paint(Paint.ANTI_ALIAS_FLAG));
            canvas.drawColor(Color.argb(0x7f, 0x10, 0x10, 0x10));

            postInvalidate();
        }).start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, new Paint(Paint.ANTI_ALIAS_FLAG));
    }
}
